import React, { useState } from 'react';
import { Button, AntdCollapse, Input, Empty, Panel, Text } from '@/components/eai-design';
import { Form, message } from 'antd';
import type { CollapseProps } from 'antd';
import { SvgIcon } from '@/components/icon';
import mcpService from '@/api/services/mcpService';
import './ToolsListPage.css';
import JsonEditor from '@/components/Textarea/JsonEditor';

interface ToolItem {
  name: string;
  description: string;
  inputSchema: {
    type: string;
    properties: Record<string, any>;
    required: string[];
  };
}

interface ToolsListPageProps {
  toolsList: ToolItem[];
  loading?: boolean;
  templateId?: string;
  headerAuth?: Record<string, any>;
  variables?: Record<string, any>;
  url?: string;
}

// Panel 和 Text 已从 eai-design 导入

const ToolsListPage: React.FC<ToolsListPageProps> = ({
  toolsList,
  loading = false,
  templateId = null,
  headerAuth = {},
  variables = {},
  url = null,
}) => {
  const [activeKey, setActiveKey] = useState<string[]>([]);
  const [selectedKey, setSelectedKey] = useState<string>('');
  const [inputValues, setInputValues] = useState<Record<string, Record<string, string>>>({});
  const [runningTools, setRunningTools] = useState<Set<string>>(new Set());
  const [toolResults, setToolResults] = useState<Record<string, string>>({});

  // 处理面板展开/折叠
  const handlePanelChange: CollapseProps['onChange'] = (keys) => {
    setActiveKey(keys as string[]);
  };

  // 处理工具项选中
  const handleToolSelect = (id: string) => {
    setSelectedKey(id);
  };

  // 处理输入值变化
  const handleInputChange = (toolName: string, fieldName: string, value: string) => {
    setInputValues((prev) => ({
      ...prev,
      [toolName]: {
        ...prev[toolName],
        [fieldName]: value,
      },
    }));
  };

  // 复制文本到剪贴板
  const handleCopyText = (text: string) => {
    navigator.clipboard.writeText(text);
    message.success('已复制到剪贴板');
  };

  // 运行工具
  const handleRunTool = async (tool: ToolItem) => {
    const toolName = tool.name;
    const toolInputs = inputValues[toolName] || {};

    // 检查必填字段
    const { required } = tool.inputSchema;
    if (required) {
      const missingFields = required.filter((field) => !toolInputs[field]);
      if (missingFields.length > 0) {
        message.error(`请填写必填字段: ${missingFields.join(', ')}`);
        return;
      }
    }
    setRunningTools((prev) => new Set(prev).add(toolName));

    try {
      const params = {
        url: url || '',
        headerAuth,
        templateId: templateId || '',
        variables,
        toolName,
        params: toolInputs,
      };

      const response = await mcpService.runTools(params);
      if (response && response.content && response.content.length > 0 && response.content[0].text) {
        setToolResults((prev) => ({
          ...prev,
          [toolName]: JSON.stringify(response, null, 2),
        }));
      }

      // message.success('工具运行成功');
    } catch (error) {
      console.error('工具运行失败:', error);
      // message.error('工具运行失败');
    } finally {
      setRunningTools((prev) => {
        const newSet = new Set(prev);
        newSet.delete(toolName);
        return newSet;
      });
    }
  };

  // 自定义面板头部
  const customPanelHeader = (tool: ToolItem) => (
    <div
      className={`flex w-full cursor-pointer items-center justify-between transition-all ${selectedKey === tool.name ? 'font-medium' : ''}`}
      onClick={() => handleToolSelect(tool.name)}
    >
      <div className="flex-1">
        <div className="font-semibold text-text-5">{tool.name}</div>
        <div className="mt-1 text-xs font-normal text-text-3">{tool.description}</div>
      </div>
      <SvgIcon
        color="#86909C"
        icon={activeKey.includes(tool.name) ? 'arrow-down' : 'arrow-right'}
        size={16}
      />
    </div>
  );

  // 生成输入字段
  const generateInputFields = (tool: ToolItem) => {
    const { properties, required } = tool.inputSchema;
    const toolInputs = inputValues[tool.name] || {};
    if (!properties) return null;

    return Object.entries(properties).map(([key, prop]: [string, any]) => (
      <div key={key} className="mb-4">
        <Form.Item
          label={<div className="font-normal text-text-5">{key}</div>}
          name={[tool.name, key]}
          rules={required && required.includes(key) ? [{ required: true, message: `请输入${key}` }] : []}
          className="formlabel formitem"
        >
          <Input
            className="rounded-md border border-[#DBDBDC]"
            placeholder={`请输入${key}`}
            value={toolInputs[key] || ''}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              handleInputChange(tool.name, key, e.target.value)
            }
          />
        </Form.Item>
        {prop.description && (
          <div className="mb-4 pl-[100px] text-xs text-text-3">{prop.description}</div>
        )}
      </div>
    ));
  };

  return (
    <div className="h-full rounded-xl bg-white p-4 md:p-6">
      {/* 页面标题 */}
      <div className="mb-6">
        <div className="mb-0 flex items-center gap-2 text-base font-semibold text-text-5">
          <SvgIcon icon="mcpTool" size="20" />
          <div>工具列表（{toolsList.length}）</div>
        </div>
      </div>

      <div className="h-[calc(100vh-162px)] space-y-4 overflow-auto pr-1">
        {loading && (
          <div className="flex h-40 items-center justify-center">
            <Text className="text-gray-500">加载中...</Text>
          </div>
        )}
        {!loading && toolsList.length === 0 && <Empty fontText="暂无数据，请先添加MCP地址" />}
        {!loading && toolsList.length > 0 && (
          <AntdCollapse
            activeKey={activeKey}
            onChange={handlePanelChange}
            bordered={false}
            expandIcon={() => null}
            className="custom-collapse space-y-4"
          >
            {toolsList.map((tool) => (
              <Panel
                key={tool.name}
                header={customPanelHeader(tool)}
                className="mb-4 overflow-hidden rounded-md"
              >
                <div className="px-4 pt-4">
                  {/* 输入字段 */}
                  <div>
                    <Form layout="horizontal" colon={false} className="custom-form-item">
                      {generateInputFields(tool)}
                    </Form>
                  </div>

                  <div className="text-right">
                    <Button
                      className="h-8 !border-[var(--brand-color)] !text-[var(--brand-color)] active:!border-[var(--brand-color-active)] active:!text-[var(--brand-color-active)] "
                      loading={runningTools.has(tool.name)}
                      onClick={() => handleRunTool(tool)}
                    >
                      {/* {runningTools.has(tool.name) ? '运行中...' : '运行'} */}
                      运行
                    </Button>
                  </div>

                  {toolResults[tool.name] && (
                    <div className="mt-4 rounded-md border border-[#DBDBDC]">
                      <div className="bg-fill-quinary flex h-10 items-center justify-between rounded-t-md px-4">
                        <span className="text-text-4">运行结果</span>
                        <span
                          onClick={() => {
                            handleCopyText(toolResults[tool.name]);
                          }}
                          className="ml-2.5 flex h-[22px] cursor-pointer items-center text-geekblue-6"
                        >
                          <SvgIcon icon="singlecopy" size={16} />
                          <span className="ml-1">复制</span>
                        </span>
                      </div>
                      <JsonEditor
                        defaultHeight={200}
                        resize={false}
                        defaultValue={toolResults[tool.name]}
                        isDisabled
                      />
                    </div>
                  )}
                </div>
              </Panel>
            ))}
          </AntdCollapse>
        )}
      </div>
    </div>
  );
};

export default ToolsListPage;
